package com.ld.translate;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.alimt.model.v20181012.TranslateECommerceRequest;
import com.aliyuncs.alimt.model.v20181012.TranslateECommerceResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class AliTranslate implements Translate{

    private static String RegionId = "cn-hangzhou";
    private static String accessKeyId   = "";
    private static String accessSecret  =   "";
    private static String scene = "title";
    private static String formatType = "text";
    private DefaultAcsClient defaultAcsClient;

    public AliTranslate(){
        DefaultProfile defaultProfile = DefaultProfile.getProfile(RegionId,accessKeyId,accessSecret);
        defaultAcsClient = new DefaultAcsClient(defaultProfile);
    }

        public JSONObject translate(String sourceText,String sourceLanguage,String targetLanguage) throws UnsupportedEncodingException, ClientException {
        TranslateECommerceRequest translateECommerceRequest = new TranslateECommerceRequest();
        translateECommerceRequest.setScene(scene);
        translateECommerceRequest.setSysMethod(MethodType.POST);
        translateECommerceRequest.setFormatType(formatType);
        translateECommerceRequest.setSourceLanguage(sourceLanguage);
        translateECommerceRequest.setSourceText(URLEncoder.encode(sourceText,"UTF-8"));
        translateECommerceRequest.setTargetLanguage(targetLanguage);
        TranslateECommerceResponse translateECommerceResponse = defaultAcsClient.getAcsResponse(translateECommerceRequest);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",translateECommerceResponse.getCode());
        jsonObject.put("data",translateECommerceResponse.getData().getTranslated());
        jsonObject.put("msg",translateECommerceResponse.getMessage());
        return jsonObject;
    }
}
